<?php
namespace app\models;

use Exception;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
use yii\helpers\Inflector;
use yii\helpers\Url;
use yii\web\UploadedFile;

/**
 * 文件上传
 *
 * Class UploadFile
 * @package app\models
 *
 * @property integer $id
 * @property integer $uid 前台用户编号，后台管理用户上传文件设置为NULL
 * @property integer $time
 * @property integer $type
 * @property integer $status
 * @property string $url
 */
class UploadFile extends ActiveRecord
{
    const TYPE_ARTICLE  = 1; // 资讯
    const TYPE_AD       = 2; // 广告
    const TYPE_SYSTEM   = 9; // 系统
    
    const STATUS_OK  = 1; // 正常
    const STATUS_DEL = 0; // 删除
    
    /**
     * 保存上传的文件
     * @param integer $type UploadFile::TYPE_*
     * @param UploadedFile $file
     * @throws Exception
     * @return UploadFile
     */
    public static function saveUpload($type, $file)
    {
        if (empty($file)) {
            throw new Exception('没有找到上传文件。');
        }
        $file_path_map = [
            UploadFile::TYPE_ARTICLE=>'article',
            UploadFile::TYPE_AD=>'ad',
            UploadFile::TYPE_SYSTEM=>'system',
        ]; // 不同类型的文件保存位置
        if (!isset($file_path_map[$type])) {
            throw new Exception('没有找到保存地址。');
        }
        $file_path = $file_path_map[$type];
        $file_path = $file_path . '/' . date('y/m/');
        $path = Yii::$app->params['upload_path'] . $file_path;
        if (!file_exists($path)) {
            if (!FileHelper::createDirectory($path)) {
                throw new Exception('无法创建目录。');
            }
        }
        $fileName = substr(uniqid(md5(rand()), true), 0, 10);
        $fileName .= '-' . Inflector::slug($file->baseName);
        $fileName .= '.' . $file->extension;
        if (!$file->saveAs($path . $fileName)) {
            Yii::error('无法保存上传文件：' . print_r($file->error, true));
            throw new Exception('无法保存文件。');
        }
        if ($type == UploadFile::TYPE_ARTICLE && Util::isImage($path . $fileName)) {
            /* @var Yii::$app->image \yii\image\ImageDriver */
            /* @var $image \yii\image\drivers\Image */
            $image = Yii::$app->image->load($path . $fileName);
            $image->resize(800, 600)->save();
        }
        $model = new UploadFile();
        $model->uid = Yii::$app->user->id;
        $model->time = time();
        $model->type = $type;
        $model->status = UploadFile::STATUS_OK;
        $model->url = $file_path . $fileName;
        if (!$model->save()) {
            Yii::error('无法保存上传文件信息：' . print_r($model->errors, true));
            throw new Exception('无法保存文件信息。');
        }
        return $model;
    }
    
    /**
     * 文件最终访问地址
     * @param boolean $scheme = false 是否同时包含URL协议及地址部分
     * @return string
     */
    public function getUrl($scheme = false)
    {
        if (strpos($this->url, 'http') === 0) {
            return $this->url;
        }
        $url = '/uploads/' . $this->url;
        if ($scheme) {
            $url = Url::base(true) . $url;
        }
        return $url;
    }

    /**
     * 根据保存路径返回访问地址
     * @param $uri string 文件相对上传目录的路径
     * @return string
     */
    public static function getFileUrl($uri)
    {
        return '/uploads/' . $uri;
    }
}
